package com.jfs.qy.chain.component;

import com.jfs.qy.chain.AbstractServerStartHandler;
import com.jfs.qy.config.component.BeatTask;
import com.jfs.qy.config.component.TaskExecutorReactor;
import com.jfs.qy.enums.NvrApiEnum;
import com.jfs.qy.service.HeartbeatService;
import com.jfs.qy.service.LogoutService;
import com.jfs.qy.session.NvrSessionStorage;
import com.jfs.qy.utils.SystemCommonUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CountDownLatch;

/**
 * @Description 责任链中心跳链 主要负责登录认证成功和Nvr保持心跳
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/4
 */
@Component(HeartbeatComponent.BEAN_NAME)
public class HeartbeatComponent extends AbstractServerStartHandler implements HeartbeatService {
    public static final String BEAN_NAME = "heartbeatComponent";
    private final TaskExecutorReactor taskExecutorReactor;
    private final SystemCommonUtils systemCommonUtils;
    private final RestTemplate restTemplate;

    private final AbstractServerStartHandler abstractServerStartHandler;

    private final LoginComponent loginComponent;

    public HeartbeatComponent(TaskExecutorReactor taskExecutorReactor,
                              SystemCommonUtils systemCommonUtils,
                              RestTemplate restTemplate,
                              @Qualifier(value = SystemInfoComponent.BEAN_NAME)
                              AbstractServerStartHandler abstractServerStartHandler,
                              @Lazy LoginComponent loginComponent) {
        this.taskExecutorReactor = taskExecutorReactor;
        this.systemCommonUtils = systemCommonUtils;
        this.restTemplate = restTemplate;
        this.abstractServerStartHandler = abstractServerStartHandler;
        this.loginComponent = loginComponent;
    }

    @Override
    public void handlerOperation() throws URISyntaxException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        //退出登录接口实现类
        LogoutService logoutService = () -> {
            final HttpEntity<?> entity = new HttpEntity<>(null, NvrSessionStorage.headers);
            String requestUrl = systemCommonUtils.getRequestUrl(NvrApiEnum.LOGOUT);
            return restTemplate.exchange(requestUrl, HttpMethod.POST, entity, String.class);
        };
        //开启任务定时发送心跳
        sendBeat(systemCommonUtils.getHeartBeatInterval(), 0L, countDownLatch,loginComponent,logoutService);
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //调用下一个链路
        abstractServerStartHandler.handlerOperation();
    }

    /**
     * 定时给nvr发送心跳
     *
     * @param second 发送心跳间隔
     */
    @Override
    public void sendBeat(long second, long initialDelay, CountDownLatch countDownLatch,LoginComponent loginComponent,LogoutService logoutService) {
        BeatTask task = new BeatTask(systemCommonUtils, restTemplate,logoutService, loginComponent,countDownLatch);
        taskExecutorReactor.schedule(task, initialDelay, second);
    }
}
